import React, { useMemo, useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Modal, Form, Input, Select, message } from 'antd';
import { env, showInMindOptions } from '@/utils/data';
import { editApi, searchApi } from '@/request/gitlab';

const { Option } = Select;

const ProjectEdit = (props: any, ref) => {
  const { handleOk, handleCancel, groups } = props;
  const [open, setOpen] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [id, setId] = useState(0);
  const [showInMind, setShowInMind] = useState();

  const groupOptions = useMemo(() => {
    if (!groups) return [];
    return groups.map((item: any) => ({
      value: item.name,
      label: item.name,
    }));
  }, [groups]);

  const onOk = () => {
    form
      .validateFields()
      .then(async (res) => {
        if (res) {
          const data = form.getFieldsValue();
          if (id) {
            data.id = id;
          }
          const result: any = await editApi(data);
          if (result.acknowledged) {
            message.success('操作成功');
            setOpen(false);
            handleOk();
          } else {
            message.error('操作失败');
          }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const onCancel = () => {
    setOpen(false);
  };

  const getData = async (projectId: number) => {
    try {
      const ret: any = await searchApi({
        id: projectId,
      });
      if (ret && ret.length) {
        const data = ret[0] || {};
        form.setFieldsValue({
          name: data.name,
          namespace: data.namespace.name,
          envs: data.envs,
          showInMind: data.showInMind,
          position: data.position,
        });
        setShowInMind(data.showInMind);
      }
    } catch (err: any) {
      console.log(err);
    }
  };

  useImperativeHandle(ref, () => ({
    handleOpen(projectid: number) {
      setOpen(true);
      getData(projectid);
      setId(projectid);
    },
  }));

  const handleShowInMind = (e) => {
    setShowInMind(e);
  };

  return (
    <Modal
      open={open}
      onOk={() => {
        onOk();
      }}
      onCancel={onCancel}
      destroyOnClose
      cancelText="取消"
      okText="确认"
      closable={false}
      width={600}
    >
      <div className="project-edit">
        <Form form={form} preserve={false} labelCol={{ span: 6 }} wrapperCol={{ span: 14 }}>
          <Form.Item label="项目名称" name="name" rules={[{ required: true, message: '请输入项目名称' }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item name="namespace" label="项目分组" rules={[{ required: true }]}>
            <Select options={groupOptions} placeholder="请选择项目组" allowClear disabled />
          </Form.Item>
          <Form.Item name="envs" label="使用环境" rules={[{ required: true }]}>
            <Select options={env} placeholder="请选择环境" allowClear mode="multiple" />
          </Form.Item>
          <Form.Item name="showInMind" label="是否展示在脑图" rules={[{ required: true }]}>
            <Select options={showInMindOptions} placeholder="请选择" allowClear onChange={handleShowInMind} />
          </Form.Item>
          {showInMind === 1 && (
            <Form.Item name="position" label="在脑图的位置" rules={[{ required: true }]}>
              <Select placeholder="请选择" allowClear>
                <Option value="left">左</Option>
                <Option value="right">右</Option>
              </Select>
            </Form.Item>
          )}
        </Form>
      </div>
    </Modal>
  );
};

export default forwardRef(ProjectEdit);
